#!/bin/bash
################################################################################
#       find.sh:	Find all instances of file (including wildcards) from an
#					index file.
#
#       Copyright 2008 Anish Mangal <anishmangal2002@gmail.com>
#
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
################################################################################

USAGE="Usage: $0 [-h] [-c] [-q] [-o operation] [-a \"args_to_grep\"] [-i index_file_name] target_file_name"

if [ "$#" == 0 ];then
	echo $USAGE
	exit 1
fi
# tricky, use the following line to obtain the last argument passed to
# the script, using indirect reference.
# see [http://www.tldp.org/LDP/abs/html/othertypesv.html]
target_file_name=${!#}
compress=0
args_to_grep=" "
index_file_name=".default.idx"
quiet=0
operation=" "
execute=0
while (( "$#" )); do
case "$1" in 
"-h")
        echo "$USAGE"
        exit 1
	;;
"-c")
        compress=1
	;;
"-q")
        quiet=1
	;;
"-o")
        operation=$2
	execute=1
	shift
	;;
"-a")
        args_to_grep=$2
	shift 
	;;
"-i")
	index_file_name=$2
	shift
	;;
esac
shift
done

if [ "$compress" == "1" ]; then
	if [ "$quiet" == "0" ]; then
		echo "Now decompressing the index file $index_file_name. File will be compressed after searching."
	fi
	gunzip $index_file_name
	index_file_name=$(echo $index_file_name|sed s/.gz// -)
fi

if [ "$quiet" == "0" ]; then
	echo "Fetching file information for $target_file_name from index file $index_file_name"
fi

found=$(grep $args_to_grep $target_file_name $index_file_name)
if [ "$execute" == "0" ]; then
    echo "$found"
fi
echo

if [ "$compress" == "1" ]; then
	#echo "Finally, compressing the index file $index_file_name"
	gzip $index_file_name
fi

if [ "$execute" == "1" ]; then
    echo $found
    $operation "$found"
fi
exit 0
